<?php
/**
 * 快递100接口调用
 */

namespace app\util;

class Express{

    const CUSTOMER = 'DDEA8B761166464BF2709171A143A495'; 

    const KEY = 'OFUYhKqL6211';

    const DOMAIN = 'http://poll.kuaidi100.com/';

    const UNIT_MAP = [
         'yuantong' => '圆通速递',
         'yuantongkuaiyun' => '圆通快运',
         'yunda' => '韵达快递',
         'yundakuaiyun' => '韵达快运',
         'shunfeng' => '顺丰速运',
         'zhongtong' => '中通快递',
         'shentong' => '申通快递',
         'jd' => '京东物流',
         'huitongkuaidi' => '百世快递',
         'baishiwuliu' => '百世快运',
         'ems' => 'EMS',
         'jtexpress' => '极兔速递',
         'youzhengbk' => '邮政标准快递',
         'youzhengguonei' => '邮政快递包裹',
         'debangwuliu' => '德邦',
         'debangkuaidi' => '德邦快递',
         'tiantian' => '天天快递',
         'zhaijisong' => '宅急送',
         'youshuwuliu' => '优速快递',
         'dsukuaidi' => 'D速快递',
    ];
    

    public $type = null;

    public $unmber = null;


    public function setType($name){
        $this->type = array_search($name, self::UNIT_MAP);
    }

    public function setNumber($unmber){
        $this->unmber = $unmber; 
    }
    
    //快递信息实时查询
    public function synquery(){
       return $this->httpQuery(self::DOMAIN . 'poll/query.do', $this->buildParams());
    }

    //快递线路图
    public function map($to){
        return $this->httpQuery(self::DOMAIN . 'poll/maptrack.do', $this->buildParams('', '', $to));
    }

    private function buildParams($phone = '', $from = '', $to = ''){
        $param = array (
            'com' => $this->type,             //快递公司编码
            'num' => $this->unmber,     //快递单号
            'phone' => $phone,                //手机号
            'from' => $from,                 //出发地城市
            'to' => $to,                   //目的地城市
            'resultv2' => '1'             //开启行政区域解析
        );
        
        //请求参数
        $data = array();
        $data["customer"] = self::CUSTOMER;
        $data["param"] = json_encode($param);
        $sign = md5($data["param"].self::KEY.$data["customer"]);
        $data["sign"] = strtoupper($sign);
        $params = "";
        foreach ($data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";              //默认UTF-8编码格式
        }
        return substr($params, 0, -1);
    }

    private function httpQuery($url, $post_data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = str_replace("\"", '"', $result );
        $data = json_decode($data, true);
        return $data;
    }
}


?>